package com.pb.metadata.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.metadata.mapper.MateCodeMapper;
import com.pb.infra.oth.entity.common.Page;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.oth.util.StringUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * 码表管理模块
 * @author liurongjun
 * @date 2021/02/22
 */
@Service
public class MateCodeService {

    /**
     * 码表DAO映射
     */
    @Resource
    private MateCodeMapper mateCodeMapper;

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    /**
     * 查询分页数据
     *
     * @param map 查询参数
     * @param page 页码
     * @return
     */
    public Result selectByPage(Map<String, Object> map, Page page){
        if (page != null && page.getPageIndex() != null && page.getPageSize() != null) {
            PageHelper.startPage(page.getPageIndex(), page.getPageSize());
        }
        map.put("tableName", StringUtil.isEmpty(map.get("tableName")) ? null : map.get("tableName").toString().toUpperCase(Locale.ENGLISH));
        List<Map<String, Object>> list = mateCodeMapper.selectByPage(map);
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    /**
     *保存码表相关信息
     * @param paramMap 保存数据
     * @return
     */
    @Transactional
    public Result insert(Map<String, Object> paramMap, HttpServletRequest request){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paramMap.put("tableNames", paramMap.get("tableName").toString().toUpperCase(Locale.ENGLISH));
        paramMap.put("dataBaseUser", paramMap.get("dataBaseUser").toString().toUpperCase(Locale.ENGLISH));
        paramMap.put("debugFlag", "0");
        paramMap.put("deleteFlag", "0");
        paramMap.put("createTime", format.format(new Date()));
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        paramMap.put("userId", userId);
        if(mateCodeMapper.selectByConstraint(paramMap)>0){       //存在则更新记录
            mateCodeMapper.updateByTableAndDataUser(paramMap);
            return Result.OK_EMPTY;
        }else{
            if(mateCodeMapper.exitCodeTable(paramMap) == 0){     //不存在此码表，则建表
                //需要把pbbase.param_code_type 表的references 权限赋予需要建表的用户
                if (mateCodeMapper.exitSchemaName(paramMap) > 0) {
                    return Result.error("-1", "数据库用户不存在");
                }
                if(!"PBBASE".equals(paramMap.get("dataBaseUser").toString().toUpperCase())){
                    mateCodeMapper.grantReferences(paramMap);    //赋权
                }
                if (!StringUtil.isEmpty(paramMap.get("corpId")) && "1".equals(paramMap.get("corpId").toString())) {
                    mateCodeMapper.createTableByCorpId(paramMap);
                } else {
                    mateCodeMapper.createTable(paramMap);            //建表
                }
            }
            paramMap.put("recordSts", "FREE");
            paramMap.put("seq", StringUtil.isEmpty(mateCodeMapper.maxTodeTableId()) == true ? "1" : mateCodeMapper.maxTodeTableId());
            mateCodeMapper.insert(paramMap);
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询数据库用户
     *
     * @return
     */
    public Result getBaseUserList(){
        List<Map<String,Object>> list =mateCodeMapper.getBaseUserList();
        return Result.ok(list);
    }

    /**修改码表相关信息
     *
     * @param paramMap 保存数据
     * @return
     */
    @Transactional
    public Result update(Map<String, Object> paramMap, HttpServletRequest request){
        paramMap.put("tableNames", paramMap.get("tableName").toString().toUpperCase());
        paramMap.put("dataBaseUser", paramMap.get("dataBaseUser").toString().toUpperCase());
        paramMap.put("deleteFlag", "0");
        paramMap.put("debugFlag", "0");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paramMap.put("updateDate", format.format(new Date()));
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        paramMap.put("userId", userId);
        if(!(paramMap.get("oldDataBaseUser").equals(paramMap.get("dataBaseUser")) && paramMap.get("oldTableName").equals(paramMap.get("tableName")))){
            if(mateCodeMapper.selectByConstraint(paramMap)>0){
                return Result.error("-1","该数据库用户已存在此应用下的码表");
            }
            return this.updateParamCodeTable(paramMap);
        }else {
            mateCodeMapper.update(paramMap);
            return Result.OK_EMPTY;
        }
    }

    /**
     * 修改码表
     * @param paramMap 请求参数
     * @return
     */
    private Result updateParamCodeTable (Map<String, Object> paramMap){
        int number = mateCodeMapper.exitCodeTable(paramMap);
        if(number == 0){
            return Result.error("-1","数据库中不存在该对象的码表");
        } else {
            mateCodeMapper.update(paramMap);
            return Result.OK_EMPTY;
        }
    }

    /**
     * 删除码表信息
     *
     * @param paramMap 请求参数
     */
    @Transactional
    public void delete(List<String> paramMap) {
        mateCodeMapper.delete(paramMap);
    }

    /**
     * 启用停用数据库用户
     *
     * @param paramMap
     */
    @Transactional
    public void startOrStop(List<Map<String,Object>> paramMap){
        for(Map map:paramMap){
            map.put("activeFlag","1".equals( map.get("activeFlag").toString())?"0":"1");
            mateCodeMapper.startOrStop(map);
        }
    }

    /**
     * 锁定码表信息
     *
     * @param paramMap 请求参数
     */
    @Transactional
    public void lockedDate(List<String> paramMap) {
        mateCodeMapper.lockedDate(paramMap);
    }

    /**
     * 提交码表信息
     *
     * @param paramMap 请求参数
     */
    @Transactional
    public void freeDate(List<String> paramMap) {
        mateCodeMapper.freeDate(paramMap);
    }
}
